from django.http import HttpResponseRedirect
from django.urls import reverse

class PrintHeadersMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        print("\n=== 请求头信息 ===")
        for header, value in request.headers.items():
            print(f"{header}: {value}")
        return self.get_response(request)

class AuthRequiredMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response
        self.exempt_urls = [
            reverse('admin:login'),
            '/accounts/login/',
            '/static/',
        ]

    def __call__(self, request):
        if not any(request.path.startswith(url) for url in self.exempt_urls):
            if not request.user.is_authenticated:
                return HttpResponseRedirect('/accounts/login/')
        return self.get_response(request)

class IPLogMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        ip = request.META.get('HTTP_X_FORWARDED_FOR') or request.META.get('REMOTE_ADDR')
        print(f"访问IP: {ip}")
        request.client_ip = ip
        return self.get_response(request)